package shuaige.jdk.多线程.锁.可重入锁_synchronized;

public class 线程同步_同时给多个操作加锁 {
    public static void main(String[] args) throws Exception {
        var ts = new Thread[]{new AddStudentThread(), new DecStudentThread(), new AddTeacherThread(), new DecTeacherThread()};
        for (var t : ts) {
            t.start();
        }
        for (var t : ts) {
            t.join();
        }
        System.out.println(Counter_加两个锁.studentCount);
        System.out.println(Counter_加两个锁.teacherCount);
    }
}

class Counter_加两个锁 {
    // 第1个锁
    public static final Object lockTeacher = new Object();
    // 第2个锁
    public static final Object lockStudent = new Object();
    public static int studentCount = 0;
    public static int teacherCount = 0;
}

class AddStudentThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter_加两个锁.lockTeacher) {
                Counter_加两个锁.studentCount += 1;
            }
        }
    }
}

class DecStudentThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter_加两个锁.lockTeacher) {
                Counter_加两个锁.studentCount -= 1;
            }
        }
    }
}

class AddTeacherThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter_加两个锁.lockStudent) {
                Counter_加两个锁.teacherCount += 1;
            }
        }
    }
}

class DecTeacherThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter_加两个锁.lockStudent) {
                Counter_加两个锁.teacherCount -= 1;
            }
        }
    }
}
